package com.bree.erp.jsf.httpsess;

import java.util.HashMap;
import java.util.Map;

import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import com.bree.erp.entity.User;
import com.bree.erp.service.UserService;

@ManagedBean(name = "userSession")
@SessionScoped
public class UserSessionData implements IUserSession {
	
	Map<SessionDataKey, Object> map = new HashMap<SessionDataKey, Object>(); 

	@EJB
	private UserService userService;
	
	@Override
	public Object get(SessionDataKey key) {
		return map.get(key);
	}
	
	@Override
	public void put(SessionDataKey key, Object data) {
		map.put(key, data);
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T> T get(SessionDataKey key, Class<T> type) {
		
		return (T) map.get(key);
	}

	public User getLoggedInUser() {
		
		String remoteUser = FacesContext.getCurrentInstance().getExternalContext().getRemoteUser();
		
		User user = userService.read(remoteUser);
		
		return user;
	}
	
	public String logout() {
	    String result="/main?faces-redirect=true";
	     
	    FacesContext context = FacesContext.getCurrentInstance();
	    HttpServletRequest request = (HttpServletRequest)context.getExternalContext().getRequest();
	     
	    try {
	      request.logout();
	    } catch (ServletException e) {
	      result = "/main?faces-redirect=true";
	    }
	     
	    return result;
	  }

}
